using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using CodeContrib.Web.Mvc.ComponentModel.DataAnnotations;

namespace CodeContrib.Web.Mvc
{
	public class FieldTemplateMetadataProvider : DataAnnotationsModelMetadataProvider
	{
		protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
		{
			var result = (DataAnnotationsModelMetadata)base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

			var templateName = attributes.OfType<ITemplateField>().Select(field => field.TemplateName).LastOrDefault();

			return new FieldTemplateMetadata(this, containerType, modelAccessor, modelType, propertyName, attributes.OfType<DisplayColumnAttribute>().FirstOrDefault(), attributes)
				       {
					       ConvertEmptyStringToNull = result.ConvertEmptyStringToNull,
					       DataTypeName = result.DataTypeName,
					       DisplayFormatString = result.DisplayFormatString,
					       DisplayName = result.DisplayName,
					       EditFormatString = result.EditFormatString,
					       HideSurroundingHtml = result.HideSurroundingHtml,
					       IsReadOnly = result.IsReadOnly,
					       NullDisplayText = result.NullDisplayText,
					       ShowForDisplay = result.ShowForDisplay,
					       ShowForEdit = result.ShowForEdit,
					       TemplateHint = templateName.AsNullIfEmpty() ?? result.TemplateHint
				       };
		}
	}
}